package hibernate.method;

import hibernate.method.interfaces.InvitationMethodsInterface;
import hibernate.model.Invitation;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;

public class InvitationMethods implements InvitationMethodsInterface{

	@SuppressWarnings("unchecked")
	@Override
	public List<Invitation> listActiveInvitationsByReceiver(
			SessionFactory sessionFactory, Session session, int invited) {
		Criteria cr = session.createCriteria(Invitation.class);
		
		Criterion to_id_res = Restrictions.eq("invited", invited);
		Criterion status = Restrictions.eq("status", 0);
	
		LogicalExpression andExp = Restrictions.and(to_id_res, status);
		cr.add(andExp);
		return cr.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Invitation> listActiveInvitationsBySender(
			SessionFactory sessionFactory, Session session, int inviting) {
		Criteria cr = session.createCriteria(Invitation.class);
		
		Criterion to_id_res = Restrictions.eq("inviting", inviting);
		Criterion status = Restrictions.eq("status", 0);
	
		LogicalExpression andExp = Restrictions.and(to_id_res, status);
		cr.add(andExp);
		return cr.list();
	}

	@Override
	public void sendInvitation(SessionFactory sessionFactory, Session session,
			int from_id, int to_id) {
		Invitation inv = new Invitation();
		inv.setInviting(from_id);
		inv.setInvited(to_id);
		inv.setStatus(0);
		session.save(inv);
		
	}

	@Override
	public void acceptInvitation(SessionFactory sessionFactory,
			Session session, Invitation inv) {
		inv.setStatus(1);
	}

	@Override
	public Invitation invitationFromId(SessionFactory sessionFactory,
			Session session, int id) {
		Object object = session.load(Invitation.class, id);
		Invitation inv = (Invitation) object;
		return inv;
	}

	@Override
	public void deleteInvitation(SessionFactory sessionFactory,
			Session session, Invitation inv) {
		session.delete(inv);
		
	}

}
